<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2 class="title">系统登录</h2>
        <p class="subtitle">欢迎使用，请登录您的账号</p>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="用户名" 
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            placeholder="密码" 
            prefix-icon="Lock"
            type="password"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <div class="remember-forgot">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary" :underline="false">忘记密码?</el-link>
        </div>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            @click="handleLogin" 
            class="login-button"
          >
            登录
          </el-button>
        </el-form-item>
        
        <div class="register-link">
          还没有账号? <el-link type="primary" :underline="false">立即注册</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import userApi from '../api/userApi';

// 路由对象
const router = useRouter();

// 表单引用
const loginFormRef = ref(null);

// 记住我选项
const rememberMe = ref(false);

// 登录状态
const loading = ref(false);

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
});

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' }
  ]
};

/**
 * 处理登录请求
 */
const handleLogin = async () => {
  if (!loginFormRef.value) return;
  
  // 表单验证
  await loginFormRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error('表单验证失败', fields);
      return;
    }
    
    try {
      loading.value = true;
      
      // 调用登录API
      const response = await userApi.authenticate({
        username: loginForm.username,
        password: loginForm.password
      });
      
      if (response.success) {
        ElMessage.success('登录成功');
        
        // 如果选择了"记住我"，可以在这里设置更长的 token 过期时间
        if (rememberMe.value) {
          localStorage.setItem('remember_login', 'true');
        }
        
        // 登录成功后跳转到首页或其他指定页面
        router.push('/');
      } else {
        ElMessage.error(response.message || '登录失败，请检查用户名和密码');
      }
    } catch (error) {
      console.error('登录出错:', error);
      
      // 针对不同错误类型提供更具体的错误信息
      if (error.message && error.message.includes('Network Error')) {
        ElMessage.error('网络错误: 请检查您的网络连接或API服务器是否可用');
      } else if (error.response) {
        // 服务器返回了错误状态码
        const status = error.response.status;
        if (status === 401) {
          ElMessage.error('用户名或密码错误');
        } else if (status === 403) {
          ElMessage.error('您没有权限访问此资源');
        } else if (status === 404) {
          ElMessage.error('登录接口不存在，请联系管理员');
        } else if (status === 500) {
          ElMessage.error('服务器内部错误，请稍后再试');
        } else {
          ElMessage.error(`请求错误 (${status}): ${error.response.data?.message || '未知错误'}`);
        }
      } else {
        ElMessage.error('登录过程中发生错误，请稍后再试');
      }
    } finally {
      loading.value = false;
    }
  });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 500;
}

.subtitle {
  font-size: 14px;
  color: #909399;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
  border-radius: 4px;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.register-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}

/* 适配移动端 */
@media (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 20px;
  }
}
</style> 